package io.webfolder.cdp.screenshot;

import static java.awt.Desktop.getDesktop;
import static java.awt.Desktop.isDesktopSupported;
import static java.nio.file.Files.createTempFile;
import static java.nio.file.Files.write;

import java.io.IOException;
import java.nio.file.Path;

import io.webfolder.cdp.Launcher;
import io.webfolder.cdp.Options;
import io.webfolder.cdp.session.Session;
import io.webfolder.cdp.session.SessionFactory;
import io.webfolder.cdp.type.constant.ImageFormat;
import io.webfolder.cdp.type.dom.BoxModel;
import io.webfolder.cdp.type.page.Viewport;

public class ScreenshotDomElement {

	public static void main(String[] args) throws IOException, InterruptedException {
		Launcher launcher = new Launcher(Options.builder().headless(true).build());

		Path file = createTempFile("screenshot", ".png");

		try (SessionFactory factory = launcher.launch(); Session session = factory.create()) {
			session.navigate("https://webfolder.io/");
			session.waitDocumentReady();

			// get x,y coordinate, width & height of the specific HTMLElement
			BoxModel boxModel = session.getBoxModel("footer");

			double x = boxModel.getContent().get(0);
			double y = boxModel.getContent().get(1);

			// this helps to capture specific coordinates of the page
			Viewport clip = new Viewport();
			clip.setScale(1D);
			clip.setWidth((double) boxModel.getWidth());
			clip.setHeight((double) boxModel.getHeight());
			clip.setX(x);
			clip.setY(y);

			byte[] data = session.captureScreenshot(Boolean.TRUE, ImageFormat.Png, 1, clip, Boolean.TRUE);
			write(file, data);
		} finally {
			launcher.kill();
		}

		if (isDesktopSupported()) {
			getDesktop().open(file.toFile());
		}
	}
}